﻿using System;
using SharePhone.Utility;

namespace SharePhone.Query
{
    public class QueryPart
    {
        public string FieldRef;
        public Expression.Operator Operator;
        private Expression.FieldType fieldType;
        private bool includeTime;
        public string val;

        public string Value
        {
            get { return val; }
            set
            {
                if ((fieldType == Expression.FieldType.DateTime ||
                     fieldType == Expression.FieldType.DateTimeWithTimeIncluded) && value != null)
                {
                    DateTime date = DateTime.MinValue;
                    if (DateTime.TryParse(value, out date))
                    {
                        val = SPUtility.CreateISO8601DateTimeFromSystemDateTime(date);
                    }
                }
                else
                    val = value;
            }
        }

        public Expression.FieldType FieldType
        {
            get { return fieldType; }
            set
            {
                fieldType = value;
                if (fieldType == Expression.FieldType.DateTimeWithTimeIncluded)
                {
                    includeTime = true;
                    fieldType = Expression.FieldType.DateTime;
                }
                else
                {
                    includeTime = false;
                    fieldType = value;
                }
            }
        }

        public override string ToString()
        {
            if (Operator == Expression.Operator.IsNotNull || Operator == Expression.Operator.IsNull)
                return String.Format("<{0}><FieldRef Name='{1}'/></{0}>", Operator, FieldRef);
            return String.Format("<{0}><FieldRef Name='{1}'/><Value Type='{2}'{4}>{3}</Value></{0}>", Operator, FieldRef,
                                 FieldType, Value, ((includeTime) ? " IncludeTimeValue='TRUE'" : ""));
        }
    }
}